<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MicroBoard | 留言板</title>

    <script src="library/jquery-3.6.0.js"></script>
    <script src="library/bootstrap3/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="library/bootstrap3/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/index.css">
    <link rel="stylesheet" href="library/font-awesome-4.7.0/css/font-awesome.min.css">
</head>
<body>
    <div class="container col-md-8 offset-md-2">
        <div class="new-message">
            <h1 class="row col" name="content"> 留言板 </h1>
            <form>
                <div class="row col">
                    <textarea required placeholder="说点啥吧 ..." class="form-control message-textarea" name="content"></textarea>
                </div>
                <div class="row name-box">
                    <div class="col-lg-3 col-md-6">
                        <span>署名</span>
                        <input class="form-control col" name="user">
                    </div>
                    <div class="col-lg-3 col-md-6">
                        <span>联系方式</span>
                        <input class="form-control col" name="email">
                    </div>
                </div>

                <div class="row col">
                    <button class="btn btn-primary" id="submit" type="button">留言</button>
                </div>
            </form>
        </div>

        <div class="message-container">
            <div class="col-md-12 col-lg-6 message-outer-wrapper"  id="messageContainerSample">
                <div class="message-wrapper">
                    <div class="row col message" info="content">
                    </div>
                    <div class="row info">
                        <div class="col-md-4" >
                            <span class="fa fa-user"></span>
                            <span info="user"></span>
                        </div>
                        <div class="col-md-4">
                            <span class="fa fa-clock-o"></span>
                            <span info="time"></span>
                        </div>
                        <div class="col-md-4">
                            <span class="fa fa-mail-reply"></span>
                            <span info="email"></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <ul class="page-list" id="pageList">
            <li id="pageRadioSample">
                <input onchange="showMessages($(this).val())" id="pageSample" type="radio" class="page-select" name="page">
                <label class="page-label" for="pageSample">
                </label>
            </li>
        </ul>

        <div style="display: flex;align-content: center;width: 220px;margin: 0 auto">
            <span id="pageCount" style="line-height: 38px;margin-right: 10px;color: gray">
            </span>
            <input class="form-control page-input" type="number" min="0">
            <button class="btn btn-primary page-jump">
                <span class="fa fa-arrow-right"></span>
            </button>
        </div>

        <div class="footer">
            作者：2019计算机科学与技术3班吴博维 <br> 指导老师: 李康顺教授 <br>
            作品完成于 2021-6-10
        </div>
    </div>

    <script>
        let sample = $("#messageContainerSample");
        let messageContainer = $(".message-container");
        sample.hide();

        let messages;
        let pageSelector;
        let pageLength = 16;

        let form = $("form");

        $("#submit").click(function(){

            let name = $("input[name=user]").val();
            let email = $("input[name=email]").val();
            let content = $("textarea[name=content]").val();

            if (content.length >= 1000) {
                alert("留言太长啦~精简一下吧（留言长度需在1000字以内）");
                return 0;
            }
            if (($.trim(content)).length === 0) {
                alert("来都来了，好歹说两句~（留言内容不能为空）");
                return 0;
            }
            if (($.trim(name)).length === 0) {
                alert("请为您的留言署名。");
                return 0;
            }
            if (name.length >= 20) {
                alert("署名过长。");
                return 0;
            }
            if (($.trim(email)).length === 0) {
                alert("请留下您的联系方式。");
                return 0;
            }
            if (email.length >= 30) {
                alert("联系方式过长。");
                return 0;
            }

            $.ajax({
                type: "POST",
                data: $("form").serialize(),
                url: "php/InsertMessage.php",
                dataType: "json",
                error: function(){

                },
                complete: function (xhr) {
                    if (xhr.responseText === "1") {
                        let box = sample.clone();
                        // let form = form;
                        let content = form.find("[name=content]").val();
                        let user = form.find("[name=user]").val();
                        let email = form.find("[name=email]").val();
                        let time = (new Date).toLocaleString();
                        // box.show();
                        let newMsg = {};
                        newMsg['content'] = content;
                        newMsg['user'] = user;
                        newMsg['created_at'] = time;
                        newMsg['email'] = email;
                        messages.unshift(newMsg);
                        $('[name=page][value="1"]').prop("checked",1);
                        showMessages(1);
                        // console.log(messages)
                    }
                }

            })
        });

        $(function(){
            $.ajax({
                type: "POST",
                url: "php/AllMessages.php",
                dataType: "json",
                error: function(){
                    alert("无法获取信息。您可能还未安装本项目，请访问/install进行安装。如需重新安装请删除 php/config.json 文件")
                },
                complete: function (xhr) {
                    messages = JSON.parse(xhr.responseText);
                    showPageList();
                    $('[name=page][value="1"]').prop("checked",1);
                    showMessages(1);
                }
            })
        });

        function addMessage(content,user,time,email) {
            let boxNum = 0;
            let box = sample.clone();
            box.find("[info=content]").text(content);
            box.find("[info=user]").text(user);
            box.find("[info=time]").text(time);
            box.find("[info=email]").text(email);
            box.attr("id","box"+(boxNum++));
            box.show();
            return box;
        }

        function showPageList() {
            let pageNum = parseInt(messages.length/pageLength)+1;
            $(".page-input").attr("max",pageNum);
            $("#pageCount").text("共 "+pageNum+" 页");
            let sample = $("#pageRadioSample");
            sample.hide();
            let list = $("#pageList");
            for (let i = 1;i <= pageNum && i <= 9;i ++) {
                let p = sample.clone();
                p.attr("id","page_li_"+i);
                p.find("input").attr("id","page_"+i);
                p.find("label").attr("for","page_"+i);
                p.find("label").text(i);
                p.find("input").attr("value",i);
                list.append(p);
                p.show();
            }
        }

        $("[name=page]").on('change',function () {
            showMessages($("input[name=page]:checked").val())
        });

        function showMessages(pageNo) {
            (async()=>{
                let select = $("[name=page][value="+'"'+pageNo+'"]');
                if (select.length !== 0) {
                    select.prop("checked",1);
                }
                else{
                    $("input[name=page]:checked").prop("checked",0)
                }
                $(".page-input").val(pageNo);
                messageContainer.find(".message-outer-wrapper").each(function () {
                    $(this).remove();
                });

                if (messages === undefined || messages.length === 0) {
                    return;
                }
                let page = pageNo;
                let start = (page-1)*pageLength;
                let end = start+(pageLength-1);
                // console.log(start);
                if (messages.length < start) {
                    return;
                }
                console.log(messages);
                for(let i = start;i <= end; i++) {
                    if (i >= messages.length) break;
                    let box = addMessage(messages[i]['content'],messages[i]['user'],messages[i]['created_at'],messages[i]['email']);
                    messageContainer.append(box);
                    box.addClass("fade-in");
                    // console.log(box);
                    box.show();
                }
            })();

            $(".page-jump").click(function () {
                showMessages($(".page-input").val())
            })
        }


    </script>
</body>
</html>